<template>
  <div class="layoutCon">
    <div class="layoutJob">
      <div :class="['jobLeft',isFly&&'fly']">
        <div class="wap">
          <el-button class="btnBack2" @click="dialogVisible=true">목록으로</el-button>
          <div class="btns2">
              <el-button class="esc" :loading="frmLoading1" @click="submitForm(0)">임시저장</el-button>
              <el-button type="primary" :loading="frmLoading2" @click="submitForm(1)">수정완료</el-button>
          </div>
        </div>
        <el-button class="btnBack" @click="dialogVisible=true">목록으로</el-button>
        <div class="card">
            <div class="info">
                <div class="avatar" @click="showAvatarEdit">
                  <img :src="userInfo&&userInfo.uthumb?userInfo.uthumb:defaultAvatar3" alt="" :onerror="errorAvatar4">
                </div>
                <div class="name">
                    <b v-if="userInfo&&userInfo.company">{{userInfo.company}}</b>
                    <span v-if="userInfo&&userInfo.email">({{userInfo.email}})</span>
                </div>
                <div class="contact">
                    <span>{{userInfo&&userInfo.phone}}</span>
                    <span>{{userInfo&&userInfo.name}}</span>
                </div>

            </div>
        </div>
        <div class="steps">
          <div class="scroll">
            <ul>
                <li :class="curStep==item.id&&'active'" v-for="(item,index) in steps" :key="index" v-html="item.title"></li>
            </ul>
          </div>
        </div>
        <div class="btns">
            <el-button v-if="editStatus==0" class="esc" :loading="frmLoading1" @click="submitForm(0)">임시저장</el-button>
            <el-button type="primary" :loading="frmLoading2" @click="submitForm(1)">{{isCreat?'등록완료':'수정하기'}}</el-button>
        </div>
        <el-dialog class="dialogMini" title="목록으로" :closeOnClickModal="false" :visible.sync="dialogVisible ">
          <div class="con">이전 화면으로 이동하시겠습니까?</div>
          <div slot="footer" class="miniFooter">
            <el-button type="primary" @click="back">확인</el-button>
            <el-button class="esc" @click="dialogVisible  = false">취소</el-button>
          </div>
        </el-dialog>
        <avatar-edit></avatar-edit>
      </div>
      <div class="jobFrm" v-loading="infoLoading">
        <h1 class="mTit">채용정보 등록하기</h1>
        <el-form :model="frm" :rules="rules" ref="jobFrm">
          <el-form-item prop="title">
            <div class="tit">
                <label>이 채용정보의 이름을 지어주세요.</label>
                <span><em>Tip.</em> 구직자에게 노출될 채용정보의 제목입니다. 돋보이는 채용정보가 될수 있도록 작성해보세요.</span>
            </div>
            <el-input placeholder="채용정보 제목" v-model="frm.title"></el-input>
          </el-form-item>
          <div class="tit">
              <label>채용직종을 선택해주세요. (최대5개)</label>
          </div>
          <div class="selectItem" v-if="index<5" v-for="(item,index) in frm.jobs" :key="item.index">
            <div class="selects">
              <el-form-item class="mb" :prop="`jobs.${index}.value`"
                :rules="{required: true, message: '채용직종을 선택해주세요.', trigger: 'change'}"
              >
                <el-cascader v-model="item.value" placeholder="직무를 선택하세요" :options="jobList" separator=" > " clearable @change="changeJobs($event,index)"></el-cascader>
              </el-form-item>
              <el-button :disabled="frm.jobs.length==1?true:false" @click="removeJob(item)" class="btnDel"></el-button>
            </div>
          </div>
          <div class="btn mb">
              <el-button v-if="frm.jobs.length<5" @click="addJob">추가하기</el-button>
          </div>
          <el-form-item :error="errors.career" prop="career">
            <div class="tit">
                <label>채용경력을 작성해주세요.</label>
            </div>
            <div class="group">
              <el-select placeholder="신입/경력 선택" v-model="frm.career">
                <el-option :label="item.value" :value="item.id" v-for="(item,index) in careerList" :key="index"></el-option>
              </el-select>
              <el-input :disabled="frm.career!=3" type="number" placeholder="최소경력(숫자)" v-model="frm.careerMin" @blur="validateCareer()"></el-input>
              <el-input :disabled="frm.career!=3" type="number" placeholder="최고경력(숫자)" v-model="frm.careerMax" @blur="validateCareer()"></el-input>
            </div>
          </el-form-item>
          <el-form-item prop="endEducation">
            <div class="tit">
                <label>최종학력을 선택해주세요.</label>
            </div>
            <div class="group">
              <el-select placeholder="최종학력 선택" v-model="frm.endEducation">
                <el-option :label="item.value" :value="item.id" v-for="(item,index) in endEducationList" :key="index"></el-option>
              </el-select>
            </div>
          </el-form-item>
          <div class="tit">
              <label>고용형태를 선택해주세요. (최대3개)</label>
          </div>
          <div class="selectItem" v-if="index<3" v-for="(item,index) in frm.employees" :key="item.index">
            <div class="selects">
                <el-form-item class="mb" :prop="`employees.${index}.id`"
                  :rules="{required: true, message: '고용형태를 선택해주세요.', trigger: 'change'}"
                >
                  <el-select placeholder="고용형태 선택" v-model="item.id">
                    <el-option :label="sub.value" :value="sub.id" v-for="(sub,index) in employeeList" :key="index"></el-option>
                  </el-select>
                </el-form-item>
                <el-button :disabled="frm.employees.length==1?true:false" @click="removeEmployee(item)" class="btnDel"></el-button>
            </div>
          </div>
          <div class="btn mb">
              <el-button v-if="frm.employees.length<3" @click="addEmployee">추가하기</el-button>
          </div>
          <div class="tit">
              <label>근무지역을 선택해주세요. (최대3개)</label>
          </div>
          <div class="selectItem" v-if="index<3" v-for="(item,index) in frm.areas" :key="item.index">
            <div class="selects">
                <el-form-item class="mb" :prop="`areas.${index}.value`"
                  :rules="{required: true, message: '근무지역을 선택해주세요.', trigger: 'change'}"
                >
                  <el-cascader class="min" v-model="item.value" placeholder="근무지역을 선택해주세요" :options="areaList" separator=" > " clearable @change="changeArea($event,index)"></el-cascader>
                </el-form-item>
                <el-button :disabled="frm.areas.length==1?true:false" @click="removeAreas(item)" class="btnDel"></el-button>
            </div>
          </div>
          <div class="btn mb">
              <el-button v-if="frm.areas.length<3" @click="addAreas">추가하기</el-button>
          </div>
          <el-form-item :error="errors.salary" prop="salaryFix">
            <div class="tit">
                <label>급여 조건을 작성해주세요.</label>
            </div>
            <div class="group">
              <el-select placeholder="급여 결정방식 선택" v-model="frm.salaryFix">
                <el-option :label="item.value" :value="item.id" v-for="(item,index) in salaryFixList" :key="index"></el-option>
              </el-select>
              <el-select placeholder="급여 형태 선택" v-model="frm.salaryUnit" @change="validateSalary()">
                <el-option :label="item.value" :value="item.id" v-for="(item,index) in salaryUnitList" :key="index"></el-option>
              </el-select>
              <el-input :disabled="frm.salaryFix==1" placeholder="최소급여" type="number" v-model="frm.salaryMin" @blur="validateSalary()"></el-input>
              <el-input :disabled="frm.salaryFix==1" placeholder="최고급여" type="number" v-model="frm.salaryMax" @blur="validateSalary()"></el-input>
            </div>
          </el-form-item>
          <el-form-item prop="job_number">
            <div class="tit">
                <label>모집인원을 작성해주세요.</label>
            </div>
            <el-input class="people" v-model="frm.job_number">
                <template slot="suffix">명</template>
            </el-input>
          </el-form-item>
          <el-form-item prop="iframe">
            <div class="tit">
                <label>상세요강을 작성해주세요.</label>
                <span><em>Tip.</em> 구직자가 귀사의 지원함에 있어, 필요한 정보를 최대한 자세하고 구체적으로 적어주세요. <br/>(모집부문/주요업무/고용형태/근무조건/지원자격/우대사항/전형일정/ 접수기간/복리후생/지원방법등)</span>
            </div>
            <summernote @checkCon="checkCon"></summernote>
          </el-form-item>
          <el-form-item prop="deadline">
            <div class="tit">
              <label>채용 마감 시간</label>
            </div>
            <el-date-picker
              class="cvDataPicker small"
              v-model="frm.deadline"
              type="date"
              :editable="false"
              value-format="yyyy-MM-dd"
              placeholder="채용 마감 시간">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <div class="tit">
                <label>채용상태</label>
                <span><em>Tip.</em> 채용대기와 채용완료 상태의 채용정보는 구직자에게 노출되지 않으며, 채용중 공고만 노출됩니다.</span>
            </div>
            <el-radio-group v-model="frm.status">
                <el-radio-button :label="0">채용대기</el-radio-button>
                <el-radio-button :label="1">채용중</el-radio-button>
                <el-radio-button :label="2">채용완료</el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="frmBom"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { jobOption, areaList, career, employee, endEducation, getSalaryFix, getSalaryUnit, getJobDetail, myCreatJob, myJobEdit } from '@/api';
import Summernote from '@/components/summernote'
import avatarEdit from '@/components/avatarEdit'

export default {
  name:'',
  components:{Summernote,avatarEdit},
  props:[],
  data(){
    var validateCareer = (rule, value, callback) => {
      if (value==='') {
        callback(new Error('채용경력을 작성해주세요.'));
      }else{
        if(this.frm.career!=3){
            callback();
          }else{
            if(this.frm.careerMin==''){
              callback(new Error('최소경력을 작성하세요.'));
            }else if(this.frm.careerMax==''){
              callback(new Error('최고경력을 작성하세요.'));
            }else if(this.frm.careerMin>=this.frm.careerMax){
              callback(new Error('최소경력이 최고경력을 초과하면 안됩니다.'));
            }else{
              callback();
            }
        }
      }
    };
    var validateSalary = (rule, value, callback) => {
      if (value==='') {
        callback(new Error('급여 결정방식을 선택해주세요.'));
      }else{
        if(this.frm.salaryUnit==''){
          callback(new Error('급여 결정방식을 선택해주세요.'));
        }else {
          if(this.frm.salaryFix==1){
            callback();
          }else{
            if(this.frm.salaryMin==''){
              callback(new Error('최소급여를 작성하세요.'));
            }else if(this.frm.salaryMax==''){
              callback(new Error('최고급여를 작성하세요.'));
            }else if(this.frm.salaryMin>=this.frm.salaryMax){
              callback(new Error('최소급여가 최고급여를 초과하면 안됩니다.'));
            }else{
              callback();
            }
          }
        }
      }
    };
    return {
      infoLoading:false,
      frmLoading1:false,
      frmLoading2:false,
      dialogVisible:false,
      isFly:false,
      steps:[
        {id:0,title:'<span>채용대기</span>(미노출)'},
        {id:1,title:'<span>채용중</span>(노출)'},
        {id:2,title:'<span>채용완료</span>(미노출)'}
      ],
      isCreat:false,
      editStatus:null,
      curStep:0,
      job_id:0,
      jobList:[],
      areaList:[],
      careerList:[],
      employeeList:[],
      endEducationList:[],
      salaryFixList:[],
      salaryUnitList:[],
      errors:{
        career:'',
        salary:'',
      },
      frm:{
          title:'',
          jobs:[
            {job1_id:'',job2_id:'',job3_id:'',value:[]}
          ],
          career:'',
          careerMin:'',
          careerMax:'',
          endEducation:'',
          employees:[
            {id:''}
          ],
          employee1:'',
          employee2:'',
          employee3:'',
          areas:[
            {area1_id:'',area2_id:'',area3_id:'',value:[]}
          ],
          salaryFix:'',
          salaryUnit:'',
          salaryMin:'',
          salaryMax:'',
          job_number:1,
          iframe:'',
          status:0,
          edit_status:0,
          deadline:''
      },
      rules:{
          title: [
            { required: true, message: '채용정보 제목을 입력해주세요.', trigger: 'blur' }
          ],
          career:[
            { required: true, validator: validateCareer, trigger: 'change' }
          ],
          endEducation:[
            { required: true, message: '학력을 선택해주세요.', trigger: 'change' }
          ],
          salaryFix:[
            { required: true, validator: validateSalary, trigger: 'change' }
          ],
          job_number:[
            { required: true, message: '모집 인원은 숫자로 입력해주세요.', trigger: 'blur' }
          ],
          iframe:[
            { required: true, message: '채용정보 상세요강을 작성해주세요.', trigger: 'blur' }
          ],
          deadline:[
            { required: true, message: '채용 마감 시간을 선택해주세요.', trigger: 'change'}
          ]
      },
      isLoading:false,
      oldJobData:null,
      oldFrmData:null
    }
  },
  computed:{
    ...mapState(['userInfo','role','errorAvatar4','defaultAvatar3'])
  },
  created(){
    this.getJobOption()
    this.getAreaList()
    this.getCareer()
    this.getEmployee()
    this.getEndEducation()
    this.getSalaryFix()
    this.getSalaryUnit()
    this.job_id=this.$route.query.job_id||0;
    this.job_id?this.getJobInfo():(this.editStatus=0);
    let _type=this.$route.query.type||0;
      _type=='new'&&(this.isCreat=true)
  },
  mounted(){
    window.addEventListener('scroll', this.handleScroll)
  },
  methods:{
    ...mapActions(['setShowAvatarEdit']),
    handleScroll() {
      let _top=window.pageYOffset;
      if(_top>10){
        this.isFly=true
      }else{
        this.isFly=false
      }
    },
    showAvatarEdit(){
      this.setShowAvatarEdit(true)
    },
    back(){
      this.$router.replace('/my/job')
    },
    async getJobInfo(){
      let res = await getJobDetail({integrated_id:this.job_id});
      if(res.code==200){
          this.oldJobData=res.data;
          let _data=res.data,_jobs=[],_areas=[];
          if(_data.jobs.length){
            _data.jobs.forEach((o,i)=>{
              let _item={job1_id:o.job1_id,job2_id:o.job2_id,job3_id:o.job3_id,value:[o.job1_id,o.job2_id,o.job3_id]}
              _jobs.push(_item)
            })
          }else{
            _jobs.push({job1_id:'',job2_id:'',job3_id:'',value:[]})
          }
          if(_data.areas.length){
            _data.areas.forEach((o,i)=>{
              let _item={area1_id:o.area1_id,area2_id:o.area2_id,area3_id:o.area3_id,value:[o.area1_id]}
                o.area2_id&&_item.value.push(o.area2_id)
                o.area3_id&&_item.value.push(o.area3_id)
              _areas.push(_item)
            })
          }else{
            _areas.push({area1_id:'',area2_id:'',area3_id:'',value:[]})
          }
          let _employees=[];
              _data.employee1&&_employees.push({id:parseInt(_data.employee1.idx)})
              _data.employee2&&_employees.push({id:parseInt(_data.employee2.idx)})
              _data.employee3&&_employees.push({id:parseInt(_data.employee3.idx)})
          this.curStep=_data.status;
          this.editStatus=_data.edit_status;
          this.frm={
              title:_data.title,
              career:_data.career&&parseInt(_data.career.idx),
              careerMin:_data.careerMin,
              careerMax:_data.careerMax,
              endEducation:_data.endEducation,
              employees:_employees,
              employee1:_data.employee1,
              employee2:_data.employee2,
              employee3:_data.employee3,
              salaryFix:_data.salaryFix>-1?_data.salaryFix:'',
              salaryUnit:_data.salaryUnit>-1?_data.salaryUnit:'',
              salaryMin:_data.salaryMin&&_data.salaryMin>-1?_data.salaryMin:'',
              salaryMax:_data.salaryMax&&_data.salaryMax>-1?_data.salaryMax:'',
              job_number:_data.job_number,
              iframe: this.getCon(_data.iframe),
              status:_data.status,
              edit_status:_data.edit_status,
              deadline:_data.deadline,
              jobs:_jobs,
              areas:_areas,
          }
          $('#summernote').summernote('code', this.getCon(_data.iframe))
          this.oldFrmData=JSON.parse(JSON.stringify(this.frm));
          this.infoLoading=false;
      }else{
        this.infoLoading=false;
      }
    },
    submitForm(type) {
      this.frm.iframe=$('#summernote').summernote('code');
      this.$refs['jobFrm'].validate( async (valid,error) => {
        if (valid) {
          let _frmParams={},_areas=[],_jobs=[]
          this.frm.areas.forEach((o,i)=>{
            let _item={};
                o.area1_id&&(_item.area1_id=o.area1_id)
                o.area2_id&&(_item.area2_id=o.area2_id)
                o.area3_id&&(_item.area3_id=o.area3_id)
                _areas.push(_item)
          })
          this.frm.jobs.forEach((o,i)=>{
            let _item={};
                o.job1_id&&(_item.job1_id=o.job1_id)
                o.job2_id&&(_item.job2_id=o.job2_id)
                o.job3_id&&(_item.job3_id=o.job3_id)
                _jobs.push(_item)
          })

          let _arry=this.frm.employees;
          this.frm.employee1=_arry[0].id;
          _frmParams={
            title:this.frm.title,
            jobs:JSON.stringify(_jobs),
            career:this.frm.career,
            careerMin:this.frm.careerMin,
            careerMax:this.frm.careerMax,
            endEducation:this.frm.endEducation,
            employee1:this.frm.employee1,
            areas:JSON.stringify(_areas),
            salaryFix:this.frm.salaryFix,
            salaryUnit:this.frm.salaryUnit,
            salaryMin:this.frm.salaryMin,
            salaryMax:this.frm.salaryMax,
            job_number:this.frm.job_number,
            iframe:this.frm.iframe,
            status:this.frm.status,
            edit_status:type,
            deadline:this.frm.deadline
          }
          // if(this.frm.salaryFix!=0){
          //   _frmParams.salaryMin=this.frm.salaryMin;
          //   _frmParams.salaryMax=this.frm.salaryMax;
          // }
          _arry[1]&&(_frmParams.employee2=_arry[1].id);
          _arry[2]&&(_frmParams.employee3=_arry[2].id);

          if(type==0){
            this.frmLoading1=true;
            this.frmLoading2=false;
          }else{
            this.frmLoading1=false;
            this.frmLoading2=true;
          }
          if(this.job_id){
            _frmParams.integrated_id=this.job_id;
            let res = await myJobEdit(_frmParams);
                if(res.code==200){
                  this.frmLoading1=false;
                  this.frmLoading2=false;
                  this.$alert('정상적으로 수정하기 완료되었습니다.', '알림', {
                    confirmButtonText: '확인',
                    callback: action => {
                      this.$router.replace('/my/job')
                    }
                  });
                }else{
                  this.$alert(res.message, '알림', {
                    confirmButtonText: '확인'
                  });
                  this.frmLoading1=false;
                  this.frmLoading2=false;
                }
          }else{
            let res = await myCreatJob(_frmParams);
                if(res.code==200){
                  this.frmLoading1=false;
                  this.frmLoading2=false;
                  this.$alert('저장이 완료되었습니다.', '알림', {
                    confirmButtonText: '확인',
                    callback: action => {
                      this.$router.replace('/my/job')
                    }
                  });
                }else{
                  this.$alert(res.message, '알림', {
                    confirmButtonText: '확인'
                  });
                  this.frmLoading1=false;
                  this.frmLoading2=false;
                }
          }
        } else {
          this.$alert('작성하지 않은 항목이 있습니다. 다시 한번 확인해 주세요.', '알림', {
            confirmButtonText: '확인'
          });
          return false;
        }
      });
    },
    async getSalaryFix(){
      let res = await getSalaryFix();
      if(res.code==200){
          this.salaryFixList=res.data;
      }
    },
    async getSalaryUnit(){
      let res = await getSalaryUnit();
      if(res.code==200){
          this.salaryUnitList=res.data;
      }
    },
    async getCareer(){
      let res = await career();
      if(res.code==200){
          this.careerList=res.data;
      }
    },
    async getEmployee(){
      let res = await employee();
      if(res.code==200){
          this.employeeList=res.data;
      }
    },
    async getEndEducation(){
      let res = await endEducation();
      if(res.code==200){
          this.endEducationList=res.data;
      }
    },
    async getJobOption(){
      let res = await jobOption({type:1,pid:0});
      if(res.code==200){
          this.jobList=this.formatData(res.data,'all_sub_jobs');
      }
    },
    changeJobs(data,index){
      this.frm.jobs[index].job1_id=data[0]
      this.frm.jobs[index].job2_id=data[1]
      this.frm.jobs[index].job3_id=data[2]
    },
    addJob(){
      this.frm.jobs.push({job1_id:'',job2_id:'',job3_id:'',value:[]});
    },
    removeJob(item){
      var index = this.frm.jobs.indexOf(item)
      if (index !== -1) {
        this.frm.jobs.splice(index, 1)
      }
    },
    async getAreaList(){
      let res = await areaList({type:1,pid:0});
      if(res.code==200){
          this.areaList=this.formatData(res.data,'all_sub_areas');
      }
    },
    changeArea(data,index){
      this.frm.areas[index].area1_id=data[0]
      this.frm.areas[index].area2_id=data[1]
      this.frm.areas[index].area3_id=data[2]
    },
    addAreas(){
      this.frm.areas.push({area1_id:'',area2_id:'',area3_id:'',value:[]});
    },
    removeAreas(item){
      var index = this.frm.areas.indexOf(item)
      if (index !== -1) {
        this.frm.areas.splice(index, 1)
      }
    },
    addEmployee(){
      this.frm.employees.push({id:''});
    },
    removeEmployee(item){
      var index = this.frm.employees.indexOf(item)
      if (index !== -1) {
        this.frm.employees.splice(index, 1)
      }
    },
    validateCareer(){
      this.$refs.jobFrm.validateField('career');
    },
    validateSalary(){
      this.$refs.jobFrm.validateField('salaryFix');
    },
    savJob(type){
      this.submitForm(type)
    },
    formatData(data,sub){
      let _arry=[]
          data.forEach((o,i)=>{
            let _item={};
                _item.label=o.name;
                _item.value=o.id;
                o[sub].length&&(_item.children=[]);
                o[sub].length&&o[sub].forEach((j,k)=>{
                  let _item2={};
                      _item2.label=j.name;
                      _item2.value=j.id;
                      j[sub].length&&(_item2.children=[]);
                      j[sub].length&&j[sub].forEach((m,n)=>{
                        let _item3={};
                            _item3.label=m.name;
                            _item3.value=m.id;
                            _item2.children.push(_item3)
                      })
                      _item.children.push(_item2)
                })
                _arry.push(_item)
          })
          return _arry
    },
    checkCon(){
      this.frm.iframe=$('#summernote').summernote('code');
      this.$refs.jobFrm.validateField('iframe');
    },
    getCon(data){
      // if(!data||data&&data.indexOf('</iframe>')>-1){
      //   return ''
      // }else{
        return data;
      // }
    }
  },
  watch:{},
  destroyed(){
    window.removeEventListener('scroll', this.handleScroll)
  }
}
</script>
<style lang="scss" scoped>
 @import "@/assets/styles/job_manager.scss";
</style>
